package com.gwsdk.paysdk.acitvityV2;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;
import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.gwsdk.open.ApiCallback;
import com.gwsdk.open.FlagControl;
import com.gwsdk.paysdk.R;
import com.gwsdk.paysdk.acitvityV2.adapter.GWCouponAdapter;
import com.gwsdk.paysdk.activity.GWWapPayActivity;
import com.gwsdk.paysdk.bean.CouponBean;
import com.gwsdk.paysdk.bean.GWPayModel;
import com.gwsdk.paysdk.bean.PersonalCenterModel;
import com.gwsdk.paysdk.bean.UserReLogin;
import com.gwsdk.paysdk.bean.VerifyCode;
import com.gwsdk.paysdk.bean.pay.ZfbPay;
import com.gwsdk.paysdk.callback.WFTWapPayCallback;
import com.gwsdk.paysdk.callback.ZFBWapPayCallback;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.config.GWConstant;
import com.gwsdk.paysdk.dialog.GWTipDialog;
import com.gwsdk.paysdk.dialog.PTBPayResultDialog;
import com.gwsdk.paysdk.entity.GamePayTypeEntity;
import com.gwsdk.paysdk.entity.PTBPayResult;
import com.gwsdk.paysdk.entity.PayResult;
import com.gwsdk.paysdk.entity.UserDiscountEntity;
import com.gwsdk.paysdk.entity.UserPTBInfo;
import com.gwsdk.paysdk.entity.WXOrderInfo;
import com.gwsdk.paysdk.entity.ZFBVerificationResult;
import com.gwsdk.paysdk.http.AliPayData;
import com.gwsdk.paysdk.http.AliPayResponse;
import com.gwsdk.paysdk.http.BaseResponse;
import com.gwsdk.paysdk.http.RequestParamUtil;
import com.gwsdk.paysdk.http.RequestUtil;
import com.gwsdk.paysdk.http.process.CouponUseableProcess;
import com.gwsdk.paysdk.http.process.PTBPayProcess;
import com.gwsdk.paysdk.http.process.PayTypeProcess;
import com.gwsdk.paysdk.http.process.UserDiscountProcess;
import com.gwsdk.paysdk.http.process.UserPtbBalanceProcess;
import com.gwsdk.paysdk.http.process.UserPtbRemainProcess;
import com.gwsdk.paysdk.http.process.WFTOrderInfoProcess;
import com.gwsdk.paysdk.http.request.CodeRequest;
import com.gwsdk.paysdk.http.request.WFTOrderInfoRequest;
import com.gwsdk.paysdk.http.request.ZFBOrderInfoRequest;
import com.gwsdk.paysdk.listener.OnMultiClickListener;
import com.gwsdk.paysdk.utils.Base64;
import com.gwsdk.paysdk.utils.GWInflaterUtils;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.GWMoneyUtils;
import com.gwsdk.paysdk.utils.JsonUtil;
import com.gwsdk.paysdk.utils.OrderInfoUtils;
import com.gwsdk.paysdk.utils.PaykeyUtil;
import com.gwsdk.paysdk.utils.ToastUtil;
import com.gwsdk.paysdk.view.RoundCornerImageView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;

public class GWPayFriendActivity extends GWBaseActivity {

    private String TAG = "GWPayFriendActivity";

    private RoundCornerImageView avatarImageView;
    private TextView tv_user_name;
    private EditText et_money;
    private TextView tv_money;
    private TextView tv_coin_number;

    private TextView next_btn;
    private View cancel_btn;
    private View inputView,infoView,payTypeView;
    private View select_pay_type;
    private TextView select_pay_type_tv;
    private int payType = 1;  //选中的支付方式：1支付宝 2微信

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏 
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏(主要功能就是去除页面弹出时顶部黑色条)

        comeOutType();
        super.onCreate(savedInstanceState);

        setContentView(R.layout.gw_activity_pay_friend);
        initView();

    }

    private void initView(){
        avatarImageView = findViewById(R.id.avatar);
        tv_user_name = findViewById(R.id.tv_user_name);
        et_money = findViewById(R.id.et_money);
        tv_money = findViewById(R.id.money);
        next_btn = findViewById(R.id.next_btn);
        cancel_btn = findViewById(R.id.cancel_btn);
        inputView = findViewById(R.id.input_view);
        infoView = findViewById(R.id.info_view);
        payTypeView = findViewById(R.id.pay_type_view);
        tv_coin_number = findViewById(R.id.coin);
        select_pay_type = findViewById(R.id.select_pay_type);
        select_pay_type_tv = findViewById(R.id.select_pay_type_tv);
        avatarImageView.setCornerRadius(20);
        Glide.with(this).load(GWPayModel.Instance().seatModel.head_picture).into(avatarImageView);
        tv_user_name.setText("为 \""+GWPayModel.Instance().seatModel.nickname+"\" 充值");

        next_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickNextBtn();
            }
        });
        cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        select_pay_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                infoView.setVisibility(View.GONE);
                payTypeView.setVisibility(View.VISIBLE);
            }
        });

        findViewById(R.id.alipay_item).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payType = 1;
                select_pay_type_tv.setText("支付宝");
                infoView.setVisibility(View.VISIBLE);
                payTypeView.setVisibility(View.GONE);
            }
        });
        findViewById(R.id.wechat_item).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payType = 2;
                select_pay_type_tv.setText("微信");
                infoView.setVisibility(View.VISIBLE);
                payTypeView.setVisibility(View.GONE);
            }
        });
    }


    private void clickNextBtn(){
        String btnStr = next_btn.getText().toString();
        if (btnStr.equals("下一步")){
            String value = et_money.getText().toString();
            if (TextUtils.isEmpty(value)){
                return;
            }
            double price = Double.parseDouble(value);
            Map<String, String> map = new HashMap<String, String>();
            map.put("price", price+"");
            RequestParams params = new RequestParams();
            String param = RequestParamUtil.getRequestParamString(map);
            try {
                params.setBodyEntity(new StringEntity(param.toString()));
            } catch (UnsupportedEncodingException e) {
                return;
            }
            tv_money.setText(value);
            HttpUtils http = new HttpUtils();
            final String url =  GWConstant.getInstance().getPayCoinRatioUrl();
            http.send(HttpRequest.HttpMethod.POST,url, params, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    String response= responseInfo.result;
                    GWLog.e(TAG, "msg:" + response);
                    double num;
                    try {
                        JSONObject json = new JSONObject(response);
                        num = json.optDouble("num");
                        tv_coin_number.setText(String.format(Locale.CHINA,"%.0f",num));
                        inputView.setVisibility(View.GONE);
                        infoView.setVisibility(View.VISIBLE);
                        next_btn.setText("确认支付");
                    }  catch (Exception e) {
                        GWLog.e(TAG, e.toString());
                    }
                }
                @Override
                public void onFailure(HttpException error, String msg) {
                    GWLog.e(TAG, "onFailure" + msg);
                }
            });
        }else {
            String price = tv_money.getText().toString();
            Map<String, String> map = new HashMap<String, String>();
            map.put("price", price+"");
            map.put("play_user_id",GWPayModel.Instance().seatModel.user_id);
            RequestParams params = new RequestParams();
            String param = RequestParamUtil.getRequestParamString(map);
            try {
                params.setBodyEntity(new StringEntity(param.toString()));
            } catch (UnsupportedEncodingException e) {
                return;
            }
            if (payType == 1){
                requestAliPay(params);
            }else {
                requestWXPay(params);
            }

        }
    }
    GWTipDialog mcTipDialog;
    private void requestAliPay(RequestParams params){
        showDialog("给支付宝下单...");
        HttpUtils http = new HttpUtils();
        final String url =  GWConstant.getInstance().getIpAddress() + "pay/alipay_coin";
        http.send(HttpRequest.HttpMethod.POST,url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                String result = responseInfo.result;
                AliPayResponse response = JsonUtil.toObj(result,AliPayResponse.class);
                if (response == null){
                    dismissDialog();
                    ToastUtil.show("订单验证失败");
                    return;
                };
                if (response.code == 200){
                    AliPayData data = response.data;
                    String tempmd5 = PaykeyUtil.stringToMD5(data.orderInfo + OrderInfoUtils.MCH_MD5KEY());
                    if (data.md5_sign.equals(tempmd5)) {
                        try {
                            String signStr = new String(Base64.decode(data.orderInfo), "utf-8");

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissDialog();
                                    handlerZfbPayResult(signStr);
                                }
                            });

                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissDialog();
                                    ToastUtil.show("订单验证失败");
                                }
                            });
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.show("订单验证失败");
                            }
                        });
                    }
                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                dismissDialog();
                GWLog.e(TAG, "onFailure" + msg);
            }
        });
    }

    private void requestWXPay(RequestParams params){
        showDialog("给微信下单...");
        ApiCallback.setWFTWapPayCallback(payCallback);
        final String url =  GWConstant.getInstance().getIpAddress() + "pay/and_weixin_coin_pay";
        WFTOrderInfoRequest request = new WFTOrderInfoRequest(payHandler);
        request.post(url,params);
    }

    private void showDialog(String message) {
        mcTipDialog = new GWTipDialog.Builder().setMessage(message).show(this, getFragmentManager());
    }

    private void dismissDialog() {
        if (null != mcTipDialog) {
            mcTipDialog.dismiss();
            mcTipDialog = null;
        }
    }

    private final WFTWapPayCallback payCallback = new WFTWapPayCallback() {
        @Override
        public void onResult(String code) {
            GWLog.e(TAG, "fun # wftPayCallback code = " + code);
            if (TextUtils.equals(code, "0")) {
                ToastUtil.show(GWPayFriendActivity.this, "支付成功");
            }else {
                ToastUtil.show(GWPayFriendActivity.this, "支付失败");
            }
            finish();
        }
    };

    private void handlerZfbPayResult(String signStr) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(GWPayFriendActivity.this);
                FlagControl.flag = true;
                // 调用支付接口，获取支付结果
                String result = alipay.pay(signStr, true);
                Message msg = new Message();
                msg.what = Constant.SDK_PAY_FLAG;
                msg.obj = result;
                payHandler.sendMessage(msg);
            }
        }).start();
    }

    private final Handler payHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ZFB_PAY_VALIDATE_FAIL:// 请求支付订单失败
                    FlagControl.flag = true;
                    ToastUtil.show(GWPayFriendActivity.this, "支付失败：" + msg.obj.toString());
                    finish();
                    break;
                case Constant.SDK_PAY_FLAG:// 支付结果
                    handlerZfbSDKResult(msg.obj);
                    break;
                case Constant.WFT_ORDERINFO_SUCCESS:
                    dismissDialog();
                    WXOrderInfo zfbwapPayOrderInfo = (WXOrderInfo) msg.obj;
                    Intent zfbWapPayintent = new Intent(GWPayFriendActivity.this, GWWapPayActivity.class);
                    zfbWapPayintent.putExtra("WapPayOrderInfo", zfbwapPayOrderInfo);
                    startActivity(zfbWapPayintent);
                    break;
                case Constant.ZFB_WAPPAY_ORDERINFO_FAIL:
                    dismissDialog();
                    ToastUtil.show(GWPayFriendActivity.this, "支付失败：" + msg.obj);
                    FlagControl.flag = true;
                    break;
                default:
                    break;
            }
        }
    };

    private void handlerZfbSDKResult(Object obj) {
        PayResult payResult = new PayResult((String) obj);
        String resultStatus = "-1";
        if (!TextUtils.isEmpty(payResult.getResultStatus())) {
            resultStatus = payResult.getResultStatus();
        }
        if (TextUtils.equals(resultStatus, "9000")) {
            ToastUtil.show(this, "支付成功");
        }else {
            ToastUtil.show(this, "支付失败");
        }
        finish();
    }

    private void comeOutType() {
        Window window = getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        window.setDimAmount(0f); //设置背景透明度   0~1
        overridePendingTransition(GWInflaterUtils.getIdByName(this,"anim","gw_scale_in"),0);// R.anim.,0);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(GWInflaterUtils.getIdByName(this,"anim","gw_scale_in"),
                GWInflaterUtils.getIdByName(this,"anim","gw_scale_out"));// R.anim.,0);
    }



}
